//用于存放关键词的数组
var keyworldArray = []

//定义变量用于接受layui的组件
var form;
var element;
var laydate;
var layer;
//当前窗口索引
var currentIndex;
var usageTypeArray = [];
var dataNotFull = false;//当前数据未填充完全
var iframeWin = window.parent[brotherWinName]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
var clickSubmit = false;//是否点击了保存
var clickVal = "";
var knowledgeBaseResultVos = existKnowledgeBaseResultVos;

layui.use(['form', 'layer', 'laydate', 'table', 'laytpl', 'element'], function () {
    element = layui.element;
    laydate = layui.laydate;
    layer = layui.layer
    form = layui.form;
    currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
    /*if(iframeWin == null || iframeWin == undefined){
        dataNotFull = true;
        //layer.msg("当前页面操作的数据不完整，无法正常的进行保存操作！");
        //设置为不可编辑
        $(function(){
            $("input").attr("disabled",true);
            $("textarea").attr("disabled",true);
        });
    }*/

    if(packageId==null || packageId==""){
        dataNotFull = true;
        //layer.msg("当前页面操作的数据不完整，无法正常的进行保存操作！");
        //设置为不可编辑
        $(function(){
            $("input").attr("disabled",true);
            $("textarea").attr("disabled",true);
        });
    }

    $("#packageId").val(packageId);
    //监听radio单选项,选择单句问答,或者多句问答
    form.on('radio(radioAnswerType)', function (data) {
        //切换到单选
        if (data.value == "ONE_TO_ONE") {

            //隐藏多选
            $("#multiSelectAnswerType").css("display", "none");
            //显示加标准答案
            $("#oneToOneanswer").css("display", "block");
            //假如有添加答案,显示
            if ($(".allAnswerDiv").length > 0) {

                //显示问题答案
                $(".allAnswerDiv").css("display", "block")
                //显示回答后操作
                $("#answerAfter").css("display", "block");
                //假如选的是转跳到指定流程显示
                if ($("#answerOperation").val() == "ASSIGN") {
                    //显示答后操作流程
                    $("#selectAnswerType").css("display", "block");
                }

            }

            //取消多轮问答流程验证
            $("#mutiSessionText").attr("lay-verify", "");
            //添加单轮问答验证
            $("#ontoOneText").attr("lay-verify", "mustNoNull")
            //添加单人答案框验证
            $(".allAnswers").attr("lay-verify", "required");
            //假如用户选择的是转跳到指定流程,添加验证
            if ($("#answerOperation").val() == "ASSIGN") {


                $("#skipFlowText").attr("lay-verify", "FlowIdNotNull");
            }

        } else {//切换到多选

            //隐藏加标准答案
            $("#oneToOneanswer").css("display", "none");
            //隐藏回答后操作
            $("#answerAfter").css("display", "none");
            //隐藏答后操作流程
            $("#selectAnswerType").css("display", "none");
            //隐藏问题答案
            $(".allAnswerDiv").css("display", "none")
            //显示多选流程选择
            $("#multiSelectAnswerType").css("display", "block");


            //取消单轮答案验证
            $("#ontoOneText").attr("lay-verify", "")

            //取消单人选择流程验证
            $("#skipFlowText").attr("lay-verify", "");

            //取消单人问答答案框验证
            $(".allAnswers").attr("lay-verify", "");

            //添加多轮问答流程验证
            $("#mutiSessionText").attr("lay-verify", "mutiSessionFlowIdNotNull");

        }
    });


    //监听单句问答答后操作的select框
    form.on('select(answerOperation)', function (data) {

        //如果用户选择转跳到指定流程,隐藏的单句流程选框显现
        if (data.value == "ASSIGN") {

            //显示选择流程框
            $("#selectAnswerType").css("display", "block")
            //添加验证
            $("#skipFlowText").attr("lay-verify", "FlowIdNotNull")

        } else {

            $("#selectAnswerType").css("display", "none")
            //取消验证
            $("#skipFlowText").attr("lay-verify", "")

        }

        form.render();
    });


    //点击layui的button,触发表单提交
    form.on('submit(addKnowledgeBase)', function (data) {
        if(dataNotFull == true){
            layer.msg("当前页面操作的数据不完整，无法进行保存操作！");
            return;
        }
        try{
            if(clickSubmit==true){
                return;
            }
            clickSubmit = true;
            var acbCbk = $("input[name='actionCodeBreak']");
            submitData = data.field;
            if(acbCbk!=null && acbCbk!=undefined){
                $("input[name='actionCodeBreak']").each(function (idx,elem) {
                    var elem=$(elem);
                    if(elem.attr("checked")!=undefined && elem.attr("checked")=="checked"){
                        submitData["actionCodeBreak"] = "true";
                    }else{
                        submitData["actionCodeBreak"] = "false";
                    }
                });
            }
            var usageTypesCbk = $("input[name='usageType']");
            if(usageTypesCbk!=null && usageTypesCbk!=undefined){
                usageTypesCbk.each(function (idx,elem) {
                    var elem = $(elem);
                    if(elem.attr("checked")!=undefined && elem.attr("checked")=="checked"){
                        usageTypeArray.push(elem.val());
                    }
                });
                console.log(usageTypeArray);
                submitData["usageTypes"] = usageTypeArray.join(",");
            }
            if(knowledgeBaseResultVos!=null && knowledgeBaseResultVos.length>0){
                for(var i=0;i<knowledgeBaseResultVos.length;i++){
                    for(var x in knowledgeBaseResultVos[i]){
                        submitData['knowledgeBaseResultVos['+i+']'+"."+x] = knowledgeBaseResultVos[i][x];
                    }
                }
            }
            console.log(submitData);
            //遍历判断关键字是否存在重复
            /*if(submitData["keyworlds"]!=null && submitData["keyworlds"]!="" && submitData["keyworlds"]!=undefined ){
                var array = submitData["keyworlds"].split(",");
                var existsWord = "";
                $.each(array,function (idx,val) {
                    if(parent.keywords!=null && parent.keywords!=undefined && parent.keywords.indexOf(","+val+",")!=-1){//在话术包的关键词中存在 且 不是原有的关键词内容
                        if(oldKeyworldString!="" ){
                            if(oldKeyworldString.indexOf(val)==-1){
                                existsWord+=val+",";
                            }
                        }else{
                            existsWord+=val+",";
                        }
                    }
                });
                if(existsWord.length>0){
                    existsWord.substring(0,existsWord.length-1);
                    parent.layer.msg(existsWord.substring(0,existsWord.length-1)+"等关键词已经在话术包中存在了");
                    return;
                }
            }*/
            console.log(refPackageId);
            if(refPackageId !=undefined && "" != refPackageId){//从别的页面进入访问
                layer.confirm('该数据属于公共知识库内容，如果编辑将会创建新的知识到项目知识库中，确定要编辑？',{icon:3, title:'提示信息'},function(index){
                    submitData["refPackageId"] = refPackageId;
                    insertDoc(submitData, 'update', currentIndex);
                });
            }else{
                insertDoc(submitData, 'update', currentIndex);
            }
        }catch (e){
            layer.msg("操作异常");
        }finally {
            clickSubmit = false;
        }
    });

    //正则表达式用于表单校验,验证
    form.verify({
        //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]

        /*//验证话术包是否为空
        packageIdNotNull: function (value, item) {


            if($("#packageId").val()==null||$("#packageId").val()==""){

                return "必须选择所属话术包";
            }

        },*/
      //验证单人流程
        FlowIdNotNull: function (value, item) {


            if ($("#skipFlowId").val() == null || $("#skipFlowId").val() == "") {

                return "必须选择流程";
            }

        },
        //验证多轮会话流程
        mutiSessionFlowIdNotNull: function (value, item) {


            if ($("#mutiSessionFlowId").val() == null || $("#mutiSessionFlowId").val() == "") {

                return "必须选择流程";
            }

        },

        //校验标题是否存在
        alreadyExisted: function (value, item) {

            var existed = false;

            //先和原来标题比一比,是不是和原来一样
            if (value != $("#originalTitle").val()) {

                //发送ajax请求到后台查找
                $.ajax({

                    data: {"termTitle": value,"packageId":$("#packageId").val()},
                    dataType: "json",
                    type: "get",
                    url: "selectByField",
                    async: false,
                    success: function (callBackData) {

                        if (callBackData.total > 0) {

                            existed = true;

                        }
                    }

                })
            }

            if (existed) {

                return "很抱歉标题已经存在";
            }
        },

        mustNoNull: function (value, item) {

            if (value == null || value.trim() == "") {

                return "请添加标准答案"
            }

        },
        title:function(value,item){

            /*if (value.length>20) {

                return "标题长度不能超过12"
            }*/

        },
        /* textarea: [/^[\n\u4E00-\u9FA5A-Za-z0-9,，。.？！?!、]+$/
            , "不能出现非法字符"
        ]*/
        textarea:function (value,item) {
            var questionflag = false;//用来标记校验结果
            $.ajax({
                type: "post",
                url: "checkTheHowQuestion",
                data: {"howAskQuestions": $("#questions").val(), "packageId": $("#packageId").val(),"id":$("#knowledgeBaseId").val()},
                dataType: "json",
                async: false,
                success: function (callBackData) {

                    if (callBackData.total > 0) {

                        var questions = $("#questions").val();

                        var questionslist=questions.split(/["\n"]+/);

                        for (var i in callBackData.records) {

                            if(questionslist.indexOf(callBackData.records[i])!=-1){

                                questionslist.splice(questionslist.indexOf(callBackData.records[i]),1);
                            }
                        }

                        questions=questionslist.join("\n").trim();

                        $("#questions").val(questions);

                        questionflag = true;

                    }
                },
                error: function (callBackData) {

                }
            })

            if (questionflag) {

                return "同一话术包或同一行业下不能有相同问法,已删除"
            }
        }
    });


    //窗体加载事件,用于回填select和关键词,问题答案
    $(function () {


        //给问法的文本域赋值
        $("#questions").val($("#howAskQuestions").val());


        //取得隐藏域的关键词字符串,是以逗号分割的
        if ($("#needKeywords").val().length > 0) {

            //将关键词分割为数组
            keyworldArray = $("#needKeywords").val().trim().split(",");

            //写入关键词小按钮
            if (keyworldArray.length > 0) {

                for (var i in keyworldArray) {
                    $("#keywordBox").append("<input  type='button' " +
                        "value='" + keyworldArray[i] + "\nx' " +
                        "class='layui-btn layui-btn-sm layui-bg-gray displayKeyword' " +
                        "onclick='GotoDeath(this)'/>");
                }

            }

        }

        //判断用户是单句问答还是多轮会话
        if ($("#oneToOne").attr("checked") == "checked") {

            //添加验证
            oneToOneVerify();

            //显示答后操作
            $("#answerAfter").css("display", 'block')

            //如果是转跳到指定流程,显示
            if ($("#answerOperation").val() == "ASSIGN") {

                $("#selectAnswerType").css("display", "block");

            }

            //显示一对一,OneToOneResult的答案
            if ($("#ontoOneText").val() != "") {
                var oneToOneResult = $("#ontoOneText").val().split(",");
                if(existKnowledgeBaseResultVos!=null){
                    for(var i=0;i<existKnowledgeBaseResultVos.length;i++){
                        var onetoOneAnswer = "<div class='layui-form-item allAnswerDiv'>"
                            + "<label class='layui-form-label '>答案:</label>"
                            + "<div class='layui-input-block'>"
                            + "<textarea height: auto' class='allAnswers layui-textarea' required lay-verify='required'"
                            + " placeholder='请输入问题答案'  id="+existKnowledgeBaseResultVos[i].id+" onblur='setanswerArray()' recordFileUrl="+existKnowledgeBaseResultVos[i].recordFileUrl+">"
                            + existKnowledgeBaseResultVos[i].content + "" +
                            "</textarea>"
                            + "<input type='button' class='layui-btn layui-btn-sm layui-bg-gray allDelete'"
                            + "value='删除' onclick='deleterandfatherDiv(this)'/>"
                            + " </div> "
                            + "</div>";


                        $("#answerAfter").before(onetoOneAnswer);
                        $("#answerAfter").css("display", "block");
                    }
                }

                /*for (var i in oneToOneResult) {

                    var onetoOneAnswer = "<div class='layui-form-item allAnswerDiv'>"
                        + "<label class='layui-form-label '>答案:</label>"
                        + "<div class='layui-input-block'>"
                        + "<textarea height: auto' class='allAnswers layui-textarea' required lay-verify='required'"
                        + " placeholder='请输入问题答案'  onblur='setanswerArray()'>" + oneToOneResult[i] + "" +
                        "</textarea>"
                        + "<input type='button' class='layui-btn layui-btn-sm layui-bg-gray allDelete'"
                        + "value='删除' onclick='deleterandfatherDiv(this)'/>"
                        + " </div> "
                        + "</div>";


                    $("#answerAfter").before(onetoOneAnswer);
                    $("#answerAfter").css("display", "block");

                }*/
            }

        } else {

            //添加验证
            sessionVerify();

            //隐藏添加标准答案
            $("#oneToOneanswer").css("display", "none");

            //让单人的答后操作等待客户回答转为默认
            $("#answerOperation").val("WAIT_CUSTOMER_ANSWER");

            //如果多轮问答,显示多轮问答流程
            $("#multiSelectAnswerType").css("display", "block");

            //重新渲染
            form.render('select');

        }

    })


    $('#keywordBox').on('contextmenu',function (e) {
        e=e||event;
        var target = e.target||e.srcElement;
        try{
            if($(target).hasClass('displayKeyword')){
                clickVal = target.value.substring(0,target.value.length-1).trim();
                console.log(clickVal);
                if(clickVal!=null && clickVal!=""){
                    var $menu = $('.keyWordMenu');
                    toggleMenu($menu, e, true);
                }
            }else{
                $('.todoMenu').css({'display': 'none'})
            }
        }catch (e){
            console.log("获取参数异常");
        }
        return false;
    });

    //编辑当前节点
    $(document).on('click', '.keyWordMenu .findSameMean', function (e) {
        console.log("查找近义词");
        try{
            e=e||event;
            var target = e.target||e.srcElement;
            showSameWordWin(clickVal);
        }catch (e){
            console.log("操作异常"+e.message());
        }finally {
            $('.todoMenu').css({'display': 'none'});
        }
    });


    /*menu操作*/
    function toggleMenu($menu, e, flag) {
        $('.todoMenu').css({'display': 'none'});
        if (flag) {
            $menu.css({"display": 'block', 'position': 'fixed', 'zIndex': '20'});
            $menu.css({'left': e.clientX, 'top': e.clientY})
        } else {
            $menu.css({'display': 'none'})
        }
    }

    /**近义词的显示框*/
    function showSameWordWin(keyword) {
        if(keyword==null || keyword=="" || keyword.trim() == null){
            layer.msg("无法获取对应的近义词操作");
            return;
        }
        $.ajax({
                type: "post",
                url: baseUrl + "/knowledgeBase/findSameMeanWord",
                data: {
                    "keyWord": keyword
                },
                dataType: "json",
                success: function (callBack) {
                    //1代表成功,0代表失败
                    if("1"==callBack.code){
                        if(callBack.total<=0){
                            layer.msg("没有找到相应的近义词");
                            return;
                        }
                        var dataList= callBack.records;
                        console.log(dataList);
                        for (var i in dataList) {
                            $("#autoKeywords").append(" <option value='" + dataList[i] + "'>" + dataList[i] + "</option>");
                        }

                        var lay = layer.open({
                            type: 1,
                            title: "近义词",
                            btn: ['保存', '取消'],
                            btn1: function (index, layero) {

                                //添加关键词
                                var keywords = $("#addKeywords option");

                                keywords.each(function (index, element) {
                                    //存入关键词数组
                                    keyworldArray.push($(element).val());
                                    //添加关键词小图标
                                    $("#keywordBox").append("<input  type='button' " +
                                        "value='" + $(element).val() + "\nx' " +
                                        "class='layui-btn layui-btn-sm layui-bg-gray displayKeyword' " +
                                        "onclick='GotoDeath(this)'/>");

                                });

                                //将数组转化为字符串,以逗号分隔,方便后台接受
                                $("#needKeywords").val(keyworldArray.join(","));
                                console.log($("#needKeywords").val());
                                //清空select框
                                $("#autoKeywords").empty();
                                $("#addKeywords").empty();
                                layer.close(index);
                            },
                            btn2: function (index, layero) {
                                //清空select框
                                $("#autoKeywords").empty();
                                $("#addKeywords").empty();
                                layer.close(index);
                            },
                            cancel:function (index, layero) {
                                //清空select框
                                $("#autoKeywords").empty();
                                $("#addKeywords").empty();
                            },
                            content: $("#selectKeyword")
                        })
                    }else{
                        layer.msg('服务器正忙,请稍后重试');
                    }
                }
            }
        );
    }
});
//自杀事件删除关键词小图标
function GotoDeath(needDeath) {

    //获取jq的DOM对象
    var addKeyword = $(needDeath);

    //取得内容
    var content = addKeyword.val().substring(0, addKeyword.val().length - 2);

    //取得所在数组的索引
    var deleteIndex = keyworldArray.indexOf(content);

    //假如索引不为空,删
    if (deleteIndex != null) {

        keyworldArray.splice(deleteIndex, 1);
    }

    $("#needKeywords").val(keyworldArray.join(","));


    addKeyword.remove();
}

//答案框点击删除,删除答案
function deleterandfatherDiv(needToDelete) {
    //删除DIV
    $(needToDelete).parent().parent().remove();

    //重新加载隐藏域数据
    setanswerArray();

    //假如一个答案没有了,答后操作隐藏
    if ($(".allAnswers").length == 0) {
        //隐藏答后操作
        $("#answerAfter").css("display", "none");
        //隐藏答后操作流程
        $("#selectAnswerType").css("display", "none");
        //恢复默认值
        $("#answerOperation").val("WAIT_CUSTOMER_ANSWER");
        //清空单句问答选择流程值
        $("#skipFlowId").val("");
        //这步重要,草他妈的layui,坑人
        form.render('select'); //刷新select选择框渲染
    }
}

//添加标准答案,弹出输入框
function addAnswer() {

    var onetoOneAnswer = "<div class='layui-form-item allAnswerDiv'>"
        + "<label class='layui-form-label '>答案:</label>"
        + "<div class='layui-input-block'>"
        + "<textarea height: auto' class='allAnswers layui-textarea' required lay-verify='required'"
        + " placeholder='请输入问题答案'  onblur='setanswerArray()'></textarea>"
        + "<input type='button' class='layui-btn layui-btn-sm layui-bg-gray allDelete'"
        + "value='删除' onclick='deleterandfatherDiv(this)'/>"
        + " </div> "
        + "</div>";


    $("#answerAfter").before(onetoOneAnswer);
    $("#answerAfter").css("display", "block");

}


/**
 *单句问答对象
 * id         id
 * conent            答法
 * recordFileUrl     录音
 *
 * */
var KnowledgeBaseResultVo = {
    buildParam: function (id, content, recordFileUrl) {
        var knowledgeBaseResultVo = {};
        knowledgeBaseResultVo.id = id;
        knowledgeBaseResultVo.content = content;
        knowledgeBaseResultVo.recordFileUrl = recordFileUrl;
        return knowledgeBaseResultVo;
    }
};

/**
 * 每次答案框失去焦点,就重新循环遍历,刷新隐藏域的值
 */
function setanswerArray() {
    knowledgeBaseResultVos = [];
    var answerArray = $(".allAnswers");

    var appendAnswer = "";


    answerArray.each(function (index, element) {

        var str = $(element).val();
        var id = $(element).attr("id");
        var recordFileUrl = $(element).attr("recordFileUrl");

        if (str != null && str.trim().length > 0) {
            knowledgeBaseResultVos.push(KnowledgeBaseResultVo.buildParam(id,str.trim(),recordFileUrl));
            appendAnswer += str.trim() + ",";
        }
    })

    $("#ontoOneText").val(appendAnswer.substring(0, appendAnswer.length - 1));

}

/**jquery-ui 根据输入内容自动查询select下拉列表
 textDom: 显示文本的jquery对象
 valueDom:隐藏值得jquery对象
 url:搜索的url
 selectType:需要搜索的数据类型
 **/
function findAndSelect(textDom,valueDom,url,selectType) {

    textDom.autocomplete({
        minLength: 0,
        source: function (request, response) {
            // $("#belongUserId").val('')//清空输入框隐藏值
            $.ajax({
                url: url,
                dataType: 'JSON',
                type: 'POST',
                data: {"text": textDom.val(),"type":selectType,"packageId":$("#packageId").val()},
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.label,
                            value: item.value
                        }
                    }));
                }
            });
        },
        focus: function (event, ui) {
            /* $(".queryText").val( ui.item.label );
             $("#queryText").val( ui.item.value );*/

            return false;
        },
        select: function (event, ui) {
            textDom.val(ui.item.label);
            valueDom.val(ui.item.value);
            return false;
        }
    });
}

//日期
function getNowFormatDate() {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    var currentdate = "'" + date.getFullYear() + "-" + month + "-" + strDate
        + " " + hours + ":" + minutes + ":" + seconds + "'";
    return currentdate;
}

//移动选择的关键词
function moveSelect(source, target) {
    target.append(source);
    source.prop("selected",false)
}

//点击按钮,从自动分词的关键词select框中选到需要添加的关键词select框中
$("#moveToRight").click(function () {
    moveSelect($("#autoKeywords option:selected"), $("#addKeywords"));
});
$("#moveToLeft").click(function () {
    moveSelect($("#addKeywords option:selected"), $("#autoKeywords"));
});
$("#moveAllToRight").click(function () {
    moveSelect($("#autoKeywords option"), $("#addKeywords"));
});
$("#moveAllToLeft").click(function () {
    moveSelect($("#addKeywords option"), $("#autoKeywords"));
});

//对问法自动进行分词,提供推荐关键词给管理员选择
$("#autoAnalysis").click(function () {

    //获取所有问法
    var allQuestions = $("#questions").val();

    //用ajax去后台,调用接口进行分词
    $.ajax({
            type: "post",
            url: "autoAnalysis",
            data: {
                "allQuestions": allQuestions,
                "keywords": keyworldArray.join(",")
            },
            dataType: "json",
            success: function (callBack) {

                //1代表成功,0代表失败
                if("1"==callBack.code){
                    var dataList= callBack.data.keywords;

                    for (var i in dataList) {

                        $("#autoKeywords").append(" <option value='" + dataList[i] + "'>" + dataList[i] + "</option>");
                    }

                    var lay = layer.open({
                        type: 1,
                        title: "自动分词",
                        btn: ['保存', '取消'],
                        btn1: function (index, layero) {

                            //添加关键词
                            var keywords = $("#addKeywords option")

                            keywords.each(function (index, element) {
                                //存入关键词数组
                                keyworldArray.push($(element).val());
                                //添加关键词小图标
                                $("#keywordBox").append("<input  type='button' " +
                                    "value='" + $(element).val() + "\nx' " +
                                    "class='layui-btn layui-btn-sm layui-bg-gray displayKeyword' " +
                                    "onclick='GotoDeath(this)'/>");

                            })

                            //将数组转化为字符串,以逗号分隔,方便后台接受
                            $("#needKeywords").val(keyworldArray.join(","));
                            console.log($("#needKeywords").val());
                            //清空select框
                            $("#autoKeywords").empty();
                            $("#addKeywords").empty();

                            layer.close(index);

                        },
                        btn2: function (index, layero) {
                            //清空select框
                            $("#autoKeywords").empty();
                            $("#addKeywords").empty();

                            layer.close(index);

                        },
                        cancel:function (index, layero) {
                            //清空select框
                            $("#autoKeywords").empty();
                            $("#addKeywords").empty();

                        },
                        content: $("#selectKeyword")
                    })
                }else{

                    layer.msg('服务器正忙,请稍后重试');
                }

            }
        }
    );
})
//输入关键词,按回车结束
$("#addKeyword").keyup(function (event) {


    //键盘码为13,代表是出车
    if (event.keyCode == 13) {

        //取出内容
        var val = $("#addKeyword").val();

        var reg = /^[\u4E00-\u9FA5A-Za-z0-9]{1,20}$/;
        //判断一波
        if (reg.test(val)) {

            //将关键词存入可以keyword数组
            keyworldArray.push(val.trim());
            //<button class='layui-btn layui-btn-xs ' onclick='GotoDeath(this)'>"+val+ "x </button>&nbsp;

            //添加关键词小图标
            $("#keywordBox").append("<input  type='button' value='" + val + "\nx' class='layui-btn layui-btn-sm layui-bg-gray displayKeyword' onclick='GotoDeath(this)'/>");

            //将数组转化为字符串,以逗号分隔,方便后台接受
            $("#needKeywords").val(keyworldArray.join(","));
        } else {

            layer.msg("关键词含有非法字符或者长度超过20");
        }

        //清空输入框
        $("#addKeyword").val("");

    }
})


//用ajax的方式提交表单
//data为表单数据,url为提交路径
function insertDoc(saveData, postUrl, needClose) {

    //弹出loading层,友好提示
    var loading = layer.load(1, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });

    $.ajax({

            data: saveData,
            type: "post",
            url: postUrl,
            dataType: "json",
            success: function (callback) {

                layer.close(loading);

                layer.msg(callback.msg);

                if (callback.code == "1") {

                    if (needClose != null) {

                        window.parent.layer.close(needClose);//执行关闭

                        window.parent.layer.msg("保存成功");

                        /* if(iframeWin.keywords!=null && iframeWin.keywords!=undefined){
                             var array = saveData["keyworlds"].split(",");
                             $.each(array,function (idx,val) {
                                 console.log(val);
                                 iframeWin.keywords+=val+",";
                             });
                         }*/
                        if(iframeWin != null && iframeWin != undefined) {
                            iframeWin.table.reload("newsListTable");
                        }
                        //parent.table.reload("newsListTable", {});
                    }


                }
            }

            ,
            error: function (callback) {

                layer.close(loading);

                window.parent.layer.msg("操作异常");
            }
        }
    )

}


//搜索并选择主动会话流程
findAndSelect($("#skipFlowText"),$("#skipFlowId"),"loadSkipFlow","MAIN");

//搜索并选择多轮会话流程
findAndSelect($("#mutiSessionText"),$("#mutiSessionFlowId"),"loadSkipFlow","MultiWheel");



//多轮会话下的验证
function sessionVerify() {

    //取消单轮答案验证
    $("#ontoOneText").attr("lay-verify", "")

    //取消单人选择流程验证
    $("#skipFlowText").attr("lay-verify", "");

    //取消单人问答答案框验证
    $(".allAnswers").attr("lay-verify", "");

    //添加多轮问答流程验证
    $("#mutiSessionText").attr("lay-verify", "mutiSessionFlowIdNotNull");
}

//单句问答验证
function oneToOneVerify() {

    //取消多轮问答流程验证
    $("#mutiSessionText").attr("lay-verify", "");
    //添加单轮问答验证
    $("#ontoOneText").attr("lay-verify", "mustNoNull")
    //添加单人答案框验证
    $(".allAnswers").attr("lay-verify", "required");
    //假如用户选择的是转跳到指定流程,添加验证
    if ($("#answerOperation").val() == "ASSIGN") {


        $("#skipFlowText").attr("lay-verify", "FlowIdNotNull");
    }

}



